package io.zbus.data.server.filter;

import io.zbus.rpc.RpcFilter;
import io.zbus.transport.Message;

/**
 * Created by laiweiwei on 18/11/08.
 */
public class ExceptionFilter implements RpcFilter {
	
    @Override
    public boolean doFilter(Message request, Message response, Throwable exception) {
		response.setHeader("Content-Type", "text/plain; charset=utf8");
    	if (
			exception instanceof IllegalArgumentException || 
			exception instanceof IllegalStateException
		) {
    		response.setStatus(406);
    	} else {
			response.setStatus(500);
		}
    	
    	Throwable cause = getCause(exception);
		response.setBody(cause.getMessage());

        return true;
    }
    
    private Throwable getCause(Throwable e) {
    	Throwable cause = e.getCause();
    	if (cause == null) {
    		return e;
    	}
		return getCause(cause);
    }

}
